package com.messi.cantonese.study;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.speech.RecognizerResult;
import com.iflytek.speech.SpeechError;
import com.iflytek.speech.SynthesizerPlayer;
import com.iflytek.speech.SpeechConfig.RATE;
import com.iflytek.speech.SynthesizerPlayerListener;
import com.iflytek.ui.RecognizerDialog;
import com.iflytek.ui.RecognizerDialogListener;
import com.iflytek.ui.SynthesizerDialog;
import com.messi.cantonese.study.http.LanguageHelperHttp;
import com.messi.cantonese.study.util.JsonParser;
import com.messi.cantonese.study.util.LogUtil;
import com.messi.cantonese.study.util.Settings;
import com.messi.cantonese.study.util.ShortCut;
import com.messi.cantonese.study.util.ToastUtil;

public class MainActivity extends Activity implements OnClickListener,
		RecognizerDialogListener,SynthesizerPlayerListener {

	private TextView result_tv,voice_btn_text;
	private EditText input_et;
	private Button submit_btn,about_tv;
	private ImageButton voice_btn;
	private ProgressBar refresh_progressbar;

	private LanguageHelperHttp httpHelper;
	private String resultString = "";
	private String dstString = "";

	// 识别Dialog
	private RecognizerDialog iatDialog;
	// 缓存，保存当前的引擎参数到下一次启动应用程序使用.
	private SharedPreferences mSharedPreferences;
	private long exitTime = 0;
	
	//合成对象.
	private SynthesizerPlayer mSynthesizerPlayer;
	//缓冲进度
	private int mPercentForBuffering = 0;
	//播放进度
	private int mPercentForPlaying = 0;
	//合成Dialog
	private SynthesizerDialog ttsDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		try {
			init();
			setMaxVolume();
			ShortCut.addShortcut(this, mSharedPreferences);
		} catch (Exception e) {
		}
	}

	private void init() {
		httpHelper = new LanguageHelperHttp();
		result_tv = (TextView) findViewById(R.id.result_tv);
		voice_btn_text = (TextView) findViewById(R.id.voice_btn_text);
		input_et = (EditText) findViewById(R.id.input_et);
		submit_btn = (Button) findViewById(R.id.submit_btn);
		about_tv = (Button) findViewById(R.id.about_tv);
		voice_btn = (ImageButton) findViewById(R.id.voice_btn);
		refresh_progressbar = (ProgressBar) findViewById(R.id.refresh_progressbar);

		// 初始化转写Dialog, appid需要在http://open.voicecloud.cn获取.
		iatDialog = new RecognizerDialog(this, "appid="
				+ getString(R.string.app_id));
		iatDialog.setListener(this);
		
		//初始化合成Dialog.
		ttsDialog = new SynthesizerDialog(this, "appid=" + getString(R.string.app_id));
		// 初始化缓存对象.
		mSharedPreferences = getSharedPreferences(getPackageName(),
				MODE_PRIVATE);
		submit_btn.setOnClickListener(this);
		voice_btn.setOnClickListener(this);
		about_tv.setOnClickListener(this);
		voice_btn_text.setOnClickListener(this);
	}
	
	private void setMaxVolume(){
		AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);  
		int max = am.getStreamMaxVolume( AudioManager.STREAM_MUSIC );        
		am.setStreamVolume(AudioManager.STREAM_MUSIC, max, 0);  
	}

	private void send() {
		Map<String, String> params = new HashMap<String, String>();
		params.put("client_id", Settings.client_id);
		params.put("q", Settings.q);
		params.put("from", Settings.from);
		params.put("to", Settings.to);
		try {
			resultString = httpHelper.doGet(Settings.baiduUrl, params, "UTF-8");
			LogUtil.DefalutLog(resultString);
			if (!TextUtils.isEmpty(resultString)) {
				dstString = JsonParser.getTranslateResult(resultString);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showResult(String result) {
		result_tv.setText(result);
	}

	class RequestAsyncTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			submit_btn.setVisibility(View.GONE);
			refresh_progressbar.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... params) {
			send();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (!TextUtils.isEmpty(dstString)) {
				if (dstString.contains("error_msg:")) {
					showToast(dstString);
				} else {
					showResult(dstString);
				}
			} else {
				showToast("连接失败，请稍后再试！");
			}
			refresh_progressbar.setVisibility(View.GONE);
			submit_btn.setVisibility(View.VISIBLE);
		}
	}

	private void showToast(String toastString) {
		Toast.makeText(getApplicationContext(), toastString, 0).show();
	}

	/**
	 * 显示转写对话框.
	 * 
	 * @param
	 */
	public void showIatDialog() {
		// 获取引擎参数
		String engine = mSharedPreferences.getString(
				getString(R.string.preference_key_iat_engine),
				getString(R.string.preference_default_iat_engine));

		// 获取area参数，POI搜索时需要传入.
		String area = null;
		// if ("poi".equals(engine)) {
		// final String defaultProvince =
		// getString(R.string.preference_default_poi_province);
		// String province = mSharedPreferences.getString(
		// getString(R.string.preference_key_poi_province),
		// defaultProvince);
		// final String defaultCity =
		// getString(R.string.preference_default_poi_city);
		// String city = mSharedPreferences.getString(
		// getString(R.string.preference_key_poi_city),
		// defaultCity);
		//
		// if (!defaultProvince.equals(province)) {
		// area = "search_area=" + province;
		// if (!defaultCity.equals(city)) {
		// area += city;
		// }
		// }
		// }

		if (TextUtils.isEmpty(area))
			area = "";
		else
			area += ",";
		// 设置转写Dialog的引擎和poi参数.
		iatDialog.setEngine(engine, area, null);

		// 设置采样率参数，由于绝大部分手机只支持8K和16K，所以设置11K和22K采样率将无法启动录音.
		String rate = mSharedPreferences.getString(
				getString(R.string.preference_key_iat_rate),
				getString(R.string.preference_default_iat_rate));
		if (rate.equals("rate8k"))
			iatDialog.setSampleRate(RATE.rate8k);
		else if (rate.equals("rate11k"))
			iatDialog.setSampleRate(RATE.rate11k);
		else if (rate.equals("rate16k"))
			iatDialog.setSampleRate(RATE.rate16k);
		else if (rate.equals("rate22k"))
			iatDialog.setSampleRate(RATE.rate22k);
		input_et.setText(null);
		// 弹出转写Dialog.
		iatDialog.show();
	}

	/**
	 * RecognizerDialogListener的"结束识别会话"回调接口. 参数详见<MSC开发指南>.
	 * 
	 * @param error
	 */
	@Override
	public void onEnd(SpeechError arg0) {
		submit();
	}

	/**
	 * RecognizerDialogListener的"返回识别结果"回调接口. 通常服务端会多次返回结果调用此接口，结果需要进行累加.
	 * 
	 * @param results
	 * @param isLast
	 */
	@Override
	public void onResults(ArrayList<RecognizerResult> results, boolean isLast) {
		StringBuilder builder = new StringBuilder();
		for (RecognizerResult recognizerResult : results) {
			builder.append(recognizerResult.text);
		}
		input_et.append(builder);
		input_et.setSelection(input_et.length());
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.submit_btn) {
			showSynDialog();
		} else if (v.getId() == R.id.voice_btn) {
			showIatDialog();
		} else if (v.getId() == R.id.about_tv) {
			Intent intent = new Intent(this, About.class);
			startActivity(intent);
		}else if (v.getId() == R.id.voice_btn_text) {
			showIatDialog();
		}
	}
	
	private void submit(){
//		Settings.q = input_et.getText().toString().trim();
//		if (!TextUtils.isEmpty(Settings.q)) {
//			new RequestAsyncTask().execute();
//		} else {
//			showToast("请输入需要翻译的内容！");
//		}
		
		
	}
	
	@Override
	public void onBackPressed() {
		if ((System.currentTimeMillis() - exitTime) > 2000) {
			Toast.makeText(getApplicationContext(), "再按一次退出程序", 0).show();
			exitTime = System.currentTimeMillis();
		} else {
			finish();
		}
	}
	
	/**合成语音
	 * 使用SynthesizerPlayer合成语音，不弹出合成Dialog.
	 * @param
	 */
	private void synthetizeInSilence() {
		if (null == mSynthesizerPlayer) {
			//创建合成对象.
			mSynthesizerPlayer = SynthesizerPlayer.createSynthesizerPlayer(
					this, "appid=" + getString(R.string.app_id));
		}

		//设置合成发音人.
		String role = "vixm";
		mSynthesizerPlayer.setVoiceName(role);

		//设置发音人语速
		int speed = 50;
		mSynthesizerPlayer.setSpeed(speed);

		//设置音量.
		int volume = 50;
		mSynthesizerPlayer.setVolume(volume);

		//设置背景音.
		String music = mSharedPreferences.getString(
				getString(R.string.preference_key_tts_music),
				getString(R.string.preference_default_tts_music));
		mSynthesizerPlayer.setBackgroundSound(music);

		//获取合成文本.
		Editable editable = input_et.getText();
		String source = null;
		if (null != editable) {
			source = editable.toString();
		}
		//进行语音合成.
		mSynthesizerPlayer.playText(source, null,this);
		ToastUtil.diaplayMesShort(getApplicationContext(), R.string.tts_toast_format);
	}
	
	/**
	 * 弹出合成Dialog，进行语音合成
	 * @param
	 */
	public void showSynDialog()
	{

		Editable editable = input_et.getText();
		String source = null;
		if (null != editable) {
			source = editable.toString();
		}
		//设置合成文本.
		ttsDialog.setText(source, null);

		//设置发音人.
		String role = "vixm";
		ttsDialog.setVoiceName(role);
		//设置语速.
		int speed = 50;
		ttsDialog.setSpeed(speed);

		//设置音量.
		int volume = 50;
		ttsDialog.setVolume(volume);

		//设置背景音.
		String music = mSharedPreferences.getString(
				getString(R.string.preference_key_tts_music),
				getString(R.string.preference_default_tts_music));
		ttsDialog.setBackgroundSound(music);

		//弹出合成Dialog
		ttsDialog.show();
	}

	/**
	 * SynthesizerPlayerListener的"播放进度"回调接口.
	 * @param percent,beginPos,endPos
	 */
	@Override
	public void onBufferPercent(int percent,int beginPos,int endPos) {
		mPercentForBuffering = percent;
	}

	@Override
	public void onPlayBegin() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPlayPaused() {
		// TODO Auto-generated method stub
		
	}

	/**
	 * SynthesizerPlayerListener的"播放进度"回调接口.
	 * @param percent,beginPos,endPos
	 */
	@Override
	public void onPlayPercent(int percent,int beginPos,int endPos) {
		mPercentForPlaying = percent;
	}

	@Override
	public void onPlayResumed() {
		// TODO Auto-generated method stub
		
	}
	
	/**
	 * SynthesizerPlayerListener的"停止播放"回调接口.
	 * @param
	 */
	@Override
	protected void onStop() {
		if (null != mSynthesizerPlayer) {
			mSynthesizerPlayer.cancel();
		}
		super.onStop();
	}
}
